package com.infinit.easyreader.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.infinit.easyreader.entity.Book;
import com.infinit.easyreader.entity.Directory;
import com.infinit.easyreader.utils.Consts;

import java.util.ArrayList;
import java.util.List;

/**
 * 类： BookDao [V 1.0.0]
 * 包含类 : com.infinit.easyreader.BookDao
 * 作用：封装Book表的相关操作
 * Created by rzy on 2016/1/30.
 */
public class BookDao extends SQLiteOpenHelper implements Consts {
    private String tableName = "books";
    private SQLiteDatabase database;

    public BookDao(Context context) {
        super(context, dataBaseName, null, 1);
        database = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {


    }


    /**
     * 作用：获得所有的数据
     *
     * @return 包含所有书籍的List
     */

    public List<Book> findAllBooks() {
        String[] selection = new String[]{
                "name",
                "isFavorite",
                "lastReadTime",
                "path",
                "dirId",
                "lastReadPosition",
                "_id"
        };
        Cursor cursor = database.query(tableName, selection, null, null, null, null, null);
        if (cursor == null || cursor.getCount() == 0) {
            return null;
        }
        List<Book> books = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            Book book = new Book();
            book.setName(cursor.getString(0));
            book.setisFavorite(cursor.getInt(1) == 1);
            book.setLastReadTime(cursor.getString(2));
            book.setPath(cursor.getString(3));
            book.setDirectoryId(cursor.getInt(4));
            book.setLastReadPosition(cursor.getLong(5));
            book.setBookId(cursor.getInt(6));
            books.add(book);
            cursor.moveToNext();
        }
        cursor.close();
        return books;
    }

    /**
     * 作用：找到指定目录下的所有书籍
     */

    public List<Book> findBooksInDirectory(int id) {
        String[] selection = new String[]{
                "name",
                "isFavorite",
                "lastReadTime",
                "path",
                "dirId",
                "lastReadPosition",
                "_id"
        };

        String whereClause = " dirId = ?";


        Cursor cursor = database.query(tableName, selection, whereClause, new String[]{id + ""}, null, null, null);
        if (cursor == null || cursor.getCount() == 0) {
            return null;
        }
        List<Book> books = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            Book book = new Book();
            book.setName(cursor.getString(0));
            book.setisFavorite(cursor.getInt(1) == 1);
            book.setLastReadTime(cursor.getString(2));
            book.setPath(cursor.getString(3));
            book.setDirectoryId(cursor.getInt(4));
            book.setLastReadPosition(cursor.getLong(5));
            book.setBookId(cursor.getInt(6));
            books.add(book);
            cursor.moveToNext();
        }
        cursor.close();
        return books;


    }


    /**
     * 作用：找到指定名字的书籍
     *
     * @param name 书籍名字
     * @return 指定的书籍
     */

    public Book findBook(String name) {
        String selectionClause = "name = ?";
        String[] selectionArgs = new String[]{
                name
        };
        String[] selection = new String[]{
                "name",
                "isFavorite",
                "lastReadTime",
                "path",
                "dirId",
                "lastReadPosition",
                "_id"
        };
        Cursor cursor = database.query(tableName, selection, selectionClause, selectionArgs, null, null, null);
        if (cursor == null || cursor.getCount() == 0) {
            return null;
        }
        cursor.moveToFirst();
        Book book = new Book();
        book.setName(cursor.getString(0));
        book.setisFavorite(cursor.getInt(1) == 1);
        book.setLastReadTime(cursor.getString(2));
        book.setPath(cursor.getString(3));
        book.setDirectoryId(cursor.getInt(4));
        book.setLastReadPosition(cursor.getLong(5));
        book.setBookId(cursor.getInt(6));
        cursor.close();
        return book;
    }


    /**
     * 作用：更新数据库
     *
     * @param book 需要传入BOOK对象
     */

    public void updateBooks(Book book) {
        String name = book.getName();
        String whereClause = "name=?";
        ContentValues values = new ContentValues();
        values.put("isFavorite", book.isFavorite() ? 1 : 0);
        values.put("lastReadTime", book.getLastReadTime());
        values.put("path", book.getPath());
        values.put("dirId", book.getDirectoryId());
        values.put("lastReadPosition", book.getLastReadPosition());

        String[] whereArgs = new String[]{
                name
        };

        database.update(tableName, values, whereClause, whereArgs);
    }


    /**
     * 作用：插入书籍方法
     *
     * @param book 需要插入的书籍
     */


    public void insertBook(Book book) {
        ContentValues values = new ContentValues();
        values.put("name", book.getName());
        values.put("isFavorite", book.isFavorite() ? 1 : 0);
        values.put("lastReadTime", book.getLastReadTime());
        values.put("path", book.getPath());
        values.put("dirId", book.getDirectoryId());
        values.put("lastReadPosition", book.getLastReadPosition());
        database.insertWithOnConflict(tableName, null, values, SQLiteDatabase.CONFLICT_IGNORE);
    }


    /**
     * 作用：删除书籍方法
     *
     * @param book Book对象
     */
    public void deleteBooks(Book book) {

        String name = book.getName();
        String whereClause = "name = ?";
        String[] whereArgs = new String[]{
                name
        };
        database.delete(tableName, whereClause, whereArgs);
    }


    /**
     * 作用：删除指定目录下所有的书籍
     *
     * @param dir 指定的Directory对象
     */
    public void deleteBooks(Directory dir) {

        int id = dir.getId();
        String whereClause = "dirId = ?";
        String[] whereArgs = new String[]{
                id + ""
        };
        database.delete(tableName, whereClause, whereArgs);
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }


    public void finish() {
        database.close();
    }


}
